function [gstruct,ngroups,groupmat]=zb_extractgroups(gstruct,shonames,histStru,landingTime)
% function [gstruct,ngroups,groupmat]=zb_extractgroups(gstruct,shonames,groupnames)
%
% GSTRUCT is a structure with an arbitrary number of groups, defined in
% field cells as .g1 .g2 .g3 etc. .gK
% The mutually exclusive partition on GSTRUCT need not cover all of
% SHONAMES, as the last group (K+1) is automatically defined as a residual 
% Hence GROUPNAMES must be [K 1] cell with the names of the groups, including the name assigned to the residual
% 
% Output 
% GSTRUCT will have new fields .n1 .n2 .n3  through .n{K+1} with the number
% of elements in each vector while .p1 .p2  through .p{K+1} will have the
% position in the vector of shocks of the elements of that group. 
% The same information is contained in the matrix GROUPMAT and can be
% accessed as GROUPMAT(1:.n{i},{i} )where i=1,...,K+1 and n{i} is the field
% above 
% 
% *SUMMARY:* All information about each of K+1 groups contained in the
% fields g{i} (members), n{i} number of elements, p{i} position 
%
% *NOTE:* when calling this function denote the output field something
% different from the input field 
% =========================================================================
% 
% SHONAMES is the name of the shocks
gstruct_names=fieldnames(gstruct); 
ngroups      =length(gstruct_names); 
nx=length(shonames); 
groupmat= zeros(nx,ngroups+1); 
groupsize=zeros(ngroups   +1,1); 
if length(histStru.groupnames{landingTime})~=ngroups+1; 
    error('GROUPNAMES must equal NGROUPS+1, i.e. including residual'); 
end 
shincluded=[]; 

for ii=1:ngroups 
    temp_names=getfield(gstruct,gstruct_names{ii}); 
    groupsize(ii)=length(temp_names); 
    groupmat(1:groupsize(ii),ii)=cellposition(temp_names,shonames); 
    gstruct=setfield(gstruct,['n',num2str(ii)],groupmat(1:groupsize(ii),ii)); 
    gstruct=setfield(gstruct,['p',num2str(ii)],groupmat(1:groupsize(ii),ii) ); 
    shincluded=[shincluded;groupmat(1:groupsize(ii),ii)]; 
end 
% Residual group     
group_res=setdiff( (1:nx)', shincluded );
groupsize(ii+1)=length(group_res);
groupmat(1:groupsize(ii+1),ii+1)=group_res;
gstruct=setfield(gstruct,['n',num2str(ii+1)],groupmat(1:groupsize(ii+1),ii+1));
gstruct=setfield(gstruct,['p',num2str(ii+1)],groupmat(1:groupsize(ii+1),ii+1) );

% Total Number of groups     
ngroups=ngroups+1;
